<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Spring+Quartz定时任务.md |  
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-develop/Spring+Quartz定时任务"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Spring+Quartz定时任务.md
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/11/11/develop/Spring+Quartz%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1/" class="article-date">
  <time datetime="2020-11-10T16:00:00.000Z" itemprop="datePublished">2020-11-11</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/develop/">develop</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">4.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">21 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>在程序中常常有定时任务的需求，例如每隔一周生成一次报表、每个月月末清空用户积分等等。Spring也提供了相应的支持，我们可以非常方便的按时执行任务。</p>
<hr>
<h2 id="项目准备"><a href="#项目准备" class="headerlink" title="项目准备"></a><strong>项目准备</strong></h2><p>**<br>**</p>
<p>这里我使用Gradle来建立项目，然后在build.gradle中添加下面一行。springVersion的值是目前最新的Spring版本’4.3.7.RELEASE’。使用Maven的话也添加相应的行。spring-context会自动引入spring-core等几个最基本的依赖。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">compile group: &#39;org.springframework&#39;, name: &#39;spring-context&#39;, version: springVersion</span><br></pre></td></tr></table></figure>



<p>定时任务属于Spring的核心支持部分，所以我们不需要再添加其他的依赖了。所以定时任务功能既可以在命令行程序中使用，也可以在Java Web程序中使用。当然后者可能使用的更广泛一些（毕竟Web程序需要一直运行的嘛）。</p>
<p>这里我们定义两个任务，后面会让它们可以定时执行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public interface IService &#123;</span><br><span class="line">    void doService();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class SimpleService implements IService &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void doService() &#123;</span><br><span class="line">        LocalTime time &#x3D; LocalTime.now();</span><br><span class="line">        System.out.println(&quot;This is a simple service:&quot; + time);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class ExpensiveTaskService implements IService &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void doService() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            Thread.sleep(TimeUnit.SECONDS.toMillis(1));</span><br><span class="line">            LocalTime time &#x3D; LocalTime.now();</span><br><span class="line">            System.out.println(&quot;This is an expensive task:&quot; + time);</span><br><span class="line">        &#125; catch (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<h2 id="Spring的任务抽象"><a href="#Spring的任务抽象" class="headerlink" title="Spring的任务抽象"></a><strong>Spring的任务抽象</strong></h2><p>**<br>**</p>
<h3 id="TaskExecutor"><a href="#TaskExecutor" class="headerlink" title="TaskExecutor"></a><strong>TaskExecutor</strong></h3><p>**<br>**</p>
<p>TaskExecutor接口是任务执行接口，类似于java.util.concurrent.Executor ，该接口只有一个方法execute(Runnable task)，用于执行任务。</p>
<p>Spring提供了一组TaskExecutor的实现，详细列表可以看这里34.2.1. TaskExecutor types。要使用它们也很简单，直接注册为Spring Bean，然后注入到程序中即可使用。</p>
<h3 id="TaskScheduler"><a href="#TaskScheduler" class="headerlink" title="TaskScheduler"></a><strong>TaskScheduler</strong></h3><p>**<br>**</p>
<p>TaskScheduler接口是定时器的抽象，它的源代码如下。可以看到，该接口包含了一组方法用于指定任务执行的时间。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public interface TaskScheduler &#123;</span><br><span class="line"></span><br><span class="line">    ScheduledFuture schedule(Runnable task, Trigger trigger);</span><br><span class="line"></span><br><span class="line">    ScheduledFuture schedule(Runnable task, Date startTime);</span><br><span class="line"></span><br><span class="line">    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);</span><br><span class="line"></span><br><span class="line">    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);</span><br><span class="line"></span><br><span class="line">    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);</span><br><span class="line"></span><br><span class="line">    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>Spring提供了两个实现，一是TimerManagerTaskScheduler，会将任务代理到CommonJ TimerManager实例。第二个是ThreadPoolTaskScheduler，当我们不需要管理线程的时候就可以使用该类。而且它还同时实现了TaskExecutor接口，所以一个ThreadPoolTaskScheduler实例即可同时用于执行定时任务。</p>
<h3 id="Trigger"><a href="#Trigger" class="headerlink" title="Trigger"></a><strong>Trigger</strong></h3><p>**<br>**</p>
<p>在定时器接口的方法中我们可以发现一个方法接受Trigger接口， 而Trigger也是一个接口，抽象了触发任务执行的触发器。</p>
<p>Trigger接口有两个实现，先说说比较简单的一个PeriodicTrigger。它直接按照给定的时间间隔触发任务执行。更常用的一个触发器是CronTrigger，它使用Cron表达式指定何时执行任务。下面是Spring官方的一个例子。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">scheduler.schedule(task, new CronTrigger(&quot;0 15 9-17 * * MON-FRI&quot;));</span><br></pre></td></tr></table></figure>



<p>关于Cron表达式的信息可以参考这篇博客QuartZ Cron表达式。另外还有一个可以在线生成Cron表达式的网站:CroMaker，不过好像需要XX才能访问。而且好像Spring不支持第二个星期一这样的定时器设置，所以如果有这样的需求，需要使用Quartz。</p>
<hr>
<h2 id="配置任务"><a href="#配置任务" class="headerlink" title="配置任务"></a><strong>配置任务</strong></h2><p>**<br>**</p>
<p>任务配置既可以使用Java配置，也可以使用XML配置。不管使用哪种方法，首先需要将要执行的方法所在的类配置为Spring Bean。例如下面就用XML配置注册了两个要执行的任务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;simpleService&quot; class&#x3D;&quot;yitian.study.service.SimpleService&quot;&#x2F;&gt;</span><br><span class="line">&lt;bean id&#x3D;&quot;expensiveTaskService&quot;</span><br><span class="line">      class&#x3D;&quot;yitian.study.service.ExpensiveTaskService&quot;&#x2F;&gt;</span><br></pre></td></tr></table></figure>



<h3 id="Java配置"><a href="#Java配置" class="headerlink" title="Java配置"></a><strong>Java配置</strong></h3><p>**<br>**</p>
<h4 id="定时任务"><a href="#定时任务" class="headerlink" title="定时任务"></a><strong>定时任务</strong></h4><p>**<br>**</p>
<p>首先看看Java配置。我们需要在配置类上添加@EnableScheduling，如果需要异步的定时任务，还需要添加@Async。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@EnableAsync</span><br><span class="line">@EnableScheduling</span><br><span class="line">public class TaskConfiguration &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>然后在要执行的方法上添加@Scheduled注解。@Scheduled注解有几个参数，任务会在相应参数的时间下执行。cron参数指定Cron表达式；fixedDelay指定任务执行的间隔，单位是毫秒；initialDelay指定当程序启动后多长时间开始执行第一次任务，单位是毫秒；zone指定任务执行时间所在的时区。下面的例子简单的指定了每隔一秒重复执行一次任务。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class SimpleService implements IService &#123;</span><br><span class="line">    @Scheduled(fixedDelay &#x3D; 1000)</span><br><span class="line">    @Override</span><br><span class="line">    public void doService() &#123;</span><br><span class="line">        LocalTime time &#x3D; LocalTime.now();</span><br><span class="line">        System.out.println(&quot;This is a simple service:&quot; + time);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="异步任务"><a href="#异步任务" class="headerlink" title="异步任务"></a><strong>异步任务</strong></h4><p>**<br>**</p>
<p>然后是异步任务，如果任务执行时间比较长的话，我们可以考虑使用异步的任务。当调用异步任务的时候，异步方法直接返回，异步任务会交由相应的任务执行器来执行。在Spring中标记异步方法很简单，直接在方法上使用@Async注解。如果需要指定异步方法使用的执行器，可以向注解传递执行器的名称。异步方法可以返回空值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@Async(&quot;otherExecutor&quot;)</span><br><span class="line">void doSomething(String s) &#123;</span><br><span class="line">    &#x2F;&#x2F; this will be executed asynchronously by &quot;otherExecutor&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>但是如果异步方法想返回其他值的话，就必须使用Future。不过不仅是java.util.concurrent.Future，异步方法还可以返回Spring的org.springframework.util.concurrent.ListenableFuture和JDK8的java.util.concurrent.CompletableFuture类型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@Async</span><br><span class="line">Future&lt;String&gt; returnSomething(int i) &#123;</span><br><span class="line">    &#x2F;&#x2F; this will be executed asynchronously</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>异步方法不仅可以用于定时任务中，在Spring的其他地方也可以使用。例如Spring Data JPA可以使用@Async编写异步的查询方法。</p>
<p>需要注意，异步方法没有对应的XML配置，如果我们想让方法是异步的，只能使用注解。当然也不是完全不行，不过就比较麻烦了，你需要使用AsyncExecutionInterceptor和AOP配合才能达到类似的效果。</p>
<p>如果需要处理异步方法的异常，我们需要实现一个AsyncUncaughtExceptionHandler。下面的异步异常处理器简单的打印异常信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void handleUncaughtException(Throwable ex, Method method, Object... params) &#123;</span><br><span class="line">        ex.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>然后通过实现AsyncConfigurer接口（Java配置方式）或者task:annotation-driven（XML配置方式）的exception-handler元素来配置。</p>
<h3 id="XML配置"><a href="#XML配置" class="headerlink" title="XML配置"></a><strong>XML配置</strong></h3><p>**<br>**</p>
<p>Spring提供了task命名空间，让配置定时任务非常简单。</p>
<p>**<br>**</p>
<h4 id="定时器"><a href="#定时器" class="headerlink" title="定时器"></a><strong>定时器</strong></h4><p>**<br>**</p>
<p>task:scheduler会注册一个ThreadPoolTaskScheduler 定时器，它只有一个属性线程池大小。默认是1，我们需要根据任务的数量指定一个合适的大小。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;task:scheduler id&#x3D;&quot;threadPoolTaskScheduler&quot;</span><br><span class="line">                pool-size&#x3D;&quot;10&quot;&#x2F;&gt;</span><br></pre></td></tr></table></figure>



<h4 id="执行器"><a href="#执行器" class="headerlink" title="执行器"></a><strong>执行器</strong></h4><p>**<br>**</p>
<p>task:executor会注册一个ThreadPoolTaskExecutor执行器，我们可以使用它的相关属性来配置该执行器。默认情况下执行队列是无限的，可能会导致JVM使用完所有内存。因此我们最好指定一个确定的数值。还有一个rejection-policy属性，指定执行器队列满时的执行策略：默认是AbortPolicy，直接抛出异常；如果当系统忙时丢弃某些任务是可接受的，可以使用DiscardPolicy或DiscardOldestPolicy策略；当系统负载较重时还可以使用CallerRunsPolicy，它不会将任务交给执行器线程，而是让调用者线程来执行该任务。最后一个就是keep-alive属性，也就是超出线程池数量 线程完成任务之后的存活时间，单位是秒。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;task:executor id&#x3D;&quot;threadPoolTaskExecutor&quot;</span><br><span class="line">               pool-size&#x3D;&quot;10&quot;</span><br><span class="line">               queue-capacity&#x3D;&quot;10&quot;&#x2F;&gt;</span><br></pre></td></tr></table></figure>



<h4 id="执行任务"><a href="#执行任务" class="headerlink" title="执行任务"></a><strong>执行任务</strong></h4><p>**<br>**</p>
<p>执行任务很简单，使用<a href="task:scheduled-tasks">task:scheduled-tasks</a>指定要执行的Bean和方法即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;task:scheduled-tasks&gt;</span><br><span class="line">        &lt;task:scheduled ref&#x3D;&quot;simpleService&quot; method&#x3D;&quot;doService&quot;</span><br><span class="line">                        cron&#x3D;&quot;*&#x2F;1 * * * * *&quot;&#x2F;&gt;</span><br><span class="line">        &lt;task:scheduled ref&#x3D;&quot;expensiveTaskService&quot; method&#x3D;&quot;doService&quot;</span><br><span class="line">                        cron&#x3D;&quot;*&#x2F;2 * * * * *&quot;&#x2F;&gt;</span><br><span class="line">    &lt;&#x2F;task:scheduled-tasks&gt;</span><br></pre></td></tr></table></figure>



<p>要设置定时的话，只需要指定相应的属性即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;task:scheduled-tasks scheduler&#x3D;&quot;myScheduler&quot;&gt;</span><br><span class="line">    &lt;task:scheduled ref&#x3D;&quot;beanA&quot; method&#x3D;&quot;methodA&quot; fixed-delay&#x3D;&quot;5000&quot; initial-delay&#x3D;&quot;1000&quot;&#x2F;&gt;</span><br><span class="line">    &lt;task:scheduled ref&#x3D;&quot;beanB&quot; method&#x3D;&quot;methodB&quot; fixed-rate&#x3D;&quot;5000&quot;&#x2F;&gt;</span><br><span class="line">    &lt;task:scheduled ref&#x3D;&quot;beanC&quot; method&#x3D;&quot;methodC&quot; cron&#x3D;&quot;*&#x2F;5 * * * * MON-FRI&quot;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;task:scheduled-tasks&gt;</span><br><span class="line"></span><br><span class="line">&lt;task:scheduler id&#x3D;&quot;myScheduler&quot; pool-size&#x3D;&quot;10&quot;&#x2F;&gt;</span><br></pre></td></tr></table></figure>



<hr>
<h2 id="Quartz集成"><a href="#Quartz集成" class="headerlink" title="Quartz集成"></a><strong>Quartz集成</strong></h2><p>**<br>**</p>
<p>Quartz是一个定时任务的库。Spring也提供了它的支持。Quartz的使用方法请查阅相应文档。这里只简单介绍一下。</p>
<p>Spring的Quartz集成在spring-context-support包中，它还需要Spring事务的支持。因此我们需要下面这样的依赖声明。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">compile group: &#39;org.springframework&#39;, name: &#39;spring-tx&#39;, version: springVersion</span><br><span class="line">   compile group: &#39;org.springframework&#39;, name: &#39;spring-context-support&#39;, version: springVersion</span><br><span class="line">   compile group: &#39;org.quartz-scheduler&#39;, name: &#39;quartz&#39;, version: &#39;2.2.3&#39;</span><br></pre></td></tr></table></figure>



<h3 id="定义任务"><a href="#定义任务" class="headerlink" title="定义任务"></a><strong>定义任务</strong></h3><p>**<br>**</p>
<p>Quartz的任务需要继承Quartz的Job接口。所以一个典型的任务可以写成这样。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public class QuartzService implements IService, Job &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void doService() &#123;</span><br><span class="line">        System.out.println(&quot;This is a quartz service&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void execute(JobExecutionContext context) throws JobExecutionException &#123;</span><br><span class="line">        System.out.println(&quot;Do something in execute method of quartz&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="JobDetailFactoryBean"><a href="#JobDetailFactoryBean" class="headerlink" title="JobDetailFactoryBean"></a><strong>JobDetailFactoryBean</strong></h3><p>**<br>**</p>
<p>JobDetailFactoryBean用来定义实现了Job接口的任务。如果需要添加更多信息，可以使用jobDataAsMap属性设置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;jobDetail&quot;</span><br><span class="line">      class&#x3D;&quot;org.springframework.scheduling.quartz.JobDetailFactoryBean&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;jobClass&quot; value&#x3D;&quot;yitian.study.service.QuartzService&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;jobDataAsMap&quot;&gt;</span><br><span class="line">        &lt;map&gt;</span><br><span class="line">            &lt;entry key&#x3D;&quot;timeout&quot; value&#x3D;&quot;10&quot;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;map&gt;</span><br><span class="line">    &lt;&#x2F;property&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br></pre></td></tr></table></figure>



<h3 id="MethodInvokingJobDetailFactoryBean"><a href="#MethodInvokingJobDetailFactoryBean" class="headerlink" title="MethodInvokingJobDetailFactoryBean"></a><strong>MethodInvokingJobDetailFactoryBean</strong></h3><p>**<br>**</p>
<p>如果任务没有实现Job接口，也可以执行，这时候需要使用MethodInvokingJobDetailFactoryBean。如果存在任务对象，使用targetObject属性，如果有任务类，使用targetClass属性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;methodJobDetail&quot; class&#x3D;&quot;org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;targetObject&quot; ref&#x3D;&quot;quartzService&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;targetMethod&quot; value&#x3D;&quot;doService&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;concurrent&quot; value&#x3D;&quot;true&quot;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br></pre></td></tr></table></figure>



<h3 id="触发器"><a href="#触发器" class="headerlink" title="触发器"></a><strong>触发器</strong></h3><p>**<br>**</p>
<p>有了任务，就可以定义触发器了。触发器有两个：SimpleTriggerFactoryBean，以指定的间隔重复执行任务；CronTriggerFactoryBean，以给定的Cron表达式执行任务。Quartz的Cron表达式比Spring 的强大，它支持第几个星期几这样的Cron表达式。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;simpleTrigger&quot; class&#x3D;&quot;org.springframework.scheduling.quartz.SimpleTriggerFactoryBean&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;jobDetail&quot; ref&#x3D;&quot;jobDetail&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;startDelay&quot; value&#x3D;&quot;0&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;repeatInterval&quot; value&#x3D;&quot;1000&quot;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br><span class="line">&lt;bean id&#x3D;&quot;cronTrigger&quot; class&#x3D;&quot;org.springframework.scheduling.quartz.CronTriggerFactoryBean&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;jobDetail&quot; ref&#x3D;&quot;methodJobDetail&quot;&#x2F;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;cronExpression&quot; value&#x3D;&quot;*&#x2F;2 * * * * ?&quot;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br></pre></td></tr></table></figure>



<h3 id="执行任务-1"><a href="#执行任务-1" class="headerlink" title="执行任务"></a><strong>执行任务</strong></h3><p>**<br>**</p>
<p>有了触发器，我们就可以执行任务了。注册一个SchedulerFactoryBean，然后将触发器的Bean引用传入即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;quartzScheduler&quot; class&#x3D;&quot;org.springframework.scheduling.quartz.SchedulerFactoryBean&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;triggers&quot;&gt;</span><br><span class="line">        &lt;list&gt;</span><br><span class="line">            &lt;ref bean&#x3D;&quot;cronTrigger&quot;&#x2F;&gt;</span><br><span class="line">            &lt;ref bean&#x3D;&quot;simpleTrigger&quot;&#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;list&gt;</span><br><span class="line">    &lt;&#x2F;property&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br></pre></td></tr></table></figure>

<p>首先说下这次主题，动态配置。没接触过定时任务的同学可以先看下此篇：</p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/laoyeye/p/6530791.html">https://www.cnblogs.com/laoyeye/p/6530791.html</a></p>
<p>定时任务实现方式千人千种，不过基础的无外乎 1、JDK 的Timer类 2、Quartz 3、SpringTask  。生产上三种方式我都有使用过。但是使用过程中用的最多的便是xml配置的方式，这种方式最简单，无代码侵入，也比较好理解。</p>
<p>但是却有个致命的缺点，比如你要改某个任务的触发时间，亦或是你要新增一个任务，暂停一个任务。怎么做？</p>
<p>停应用！改XML配置！重新启动！</p>
<p>是不是很致命。最近重新研究了下Quartz的配置，实现了不停机添加、暂停、删除、立即触发任务的方法，在本篇分享出来，其实也不算是完全的研究，在上家公司已经有大佬实现了，这次是也是基于大佬的理解重新实现下。</p>
<p><strong>管理界面：</strong></p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/oTKHc6F8tsgtNAMpibdQz4fFJicpnDjOvglRrurO1KKHcmzvicUo2ZFF588gvusEc9iaYNMrILpky5hdt6GpSrZcsw/640?tp=webp&wxfrom=5&wx_lazy=1&wx_co=1" alt="img"></p>
<p> 效果图：实在不知道该跑什么了，每隔十秒打一段话吧</p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/oTKHc6F8tsgtNAMpibdQz4fFJicpnDjOvggJQ72D7DTSOWHAq53B2NwSibVrbs2Q0cLGJeffDAUGg9E7ciacK9DNnQ/640?tp=webp&wxfrom=5&wx_lazy=1&wx_co=1" alt="img"></p>
<h3 id="maven依赖"><a href="#maven依赖" class="headerlink" title="maven依赖"></a><strong>maven依赖</strong></h3><p>使用spring boot做框架支持</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- quartz --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.quartz-scheduler&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;quartz&lt;&#x2F;artifactId&gt;</span><br><span class="line">    &lt;version&gt;2.2.1&lt;&#x2F;version&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-context-support&lt;&#x2F;artifactId&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br></pre></td></tr></table></figure>

<p>数据表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE &#96;sys_task&#96; (</span><br><span class="line">  &#96;id&#96; bigint(20) NOT NULL AUTO_INCREMENT,</span><br><span class="line">  &#96;job_name&#96; varchar(255) DEFAULT NULL COMMENT &#39;任务名&#39;,</span><br><span class="line">  &#96;description&#96; varchar(255) DEFAULT NULL COMMENT &#39;任务描述&#39;,</span><br><span class="line">  &#96;cron_expression&#96; varchar(255) DEFAULT NULL COMMENT &#39;cron表达式&#39;,</span><br><span class="line">  &#96;bean_class&#96; varchar(255) DEFAULT NULL COMMENT &#39;任务执行时调用哪个类的方法 包名+类名&#39;,</span><br><span class="line">  &#96;job_status&#96; varchar(255) DEFAULT NULL COMMENT &#39;任务状态&#39;,</span><br><span class="line">  &#96;job_group&#96; varchar(255) DEFAULT NULL COMMENT &#39;任务分组&#39;,</span><br><span class="line">  &#96;create_user&#96; varchar(64) DEFAULT NULL COMMENT &#39;创建者&#39;,</span><br><span class="line">  &#96;create_time&#96; datetime DEFAULT NULL COMMENT &#39;创建时间&#39;,</span><br><span class="line">  &#96;update_user&#96; varchar(64) DEFAULT NULL COMMENT &#39;更新者&#39;,</span><br><span class="line">  &#96;update_time&#96; datetime DEFAULT NULL COMMENT &#39;更新时间&#39;,</span><br><span class="line">  PRIMARY KEY (&#96;id&#96;)</span><br><span class="line">) ENGINE&#x3D;MyISAM AUTO_INCREMENT&#x3D;32 DEFAULT CHARSET&#x3D;utf8;</span><br></pre></td></tr></table></figure>

<p>实现步骤</p>
<p>① 启动项目，启动task监听</p>
<p>② 读取数据库，将开启的任务job和trigger加载到scheduler调度器</p>
<p>③ 根据任务调度运行job类</p>
<p>④ 每次运行利用AdaptableJobFactory实例化job类，以便注入要运行的service</p>
<p>听着是不是很简单，但却还是一头雾水，且听我慢慢道来~~</p>
<h3 id="代码逻辑"><a href="#代码逻辑" class="headerlink" title="代码逻辑"></a>代码逻辑</h3><p><strong>第一步：启动项目，加载监听</strong></p>
<p><strong>Quartz配置</strong></p>
<p>Springboot的配置方法，常规Spring项目可以在xml中配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">public class QuartzConfigration &#123;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    private JobFactory jobFactory;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public SchedulerFactoryBean schedulerFactoryBean() &#123;</span><br><span class="line">        SchedulerFactoryBean schedulerFactoryBean &#x3D; new SchedulerFactoryBean();</span><br><span class="line">        try &#123;</span><br><span class="line">            schedulerFactoryBean.setOverwriteExistingJobs(true);</span><br><span class="line">            schedulerFactoryBean.setQuartzProperties(quartzProperties());</span><br><span class="line">            schedulerFactoryBean.setJobFactory(jobFactory);</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        return schedulerFactoryBean;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 指定quartz.properties，可在配置文件中配置相关属性</span><br><span class="line">    @Bean</span><br><span class="line">    public Properties quartzProperties() throws IOException &#123;</span><br><span class="line">        PropertiesFactoryBean propertiesFactoryBean &#x3D; new PropertiesFactoryBean();</span><br><span class="line">        propertiesFactoryBean.setLocation(new ClassPathResource(&quot;&#x2F;config&#x2F;quartz.properties&quot;));</span><br><span class="line">        propertiesFactoryBean.afterPropertiesSet();</span><br><span class="line">        return propertiesFactoryBean.getObject();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; 创建schedule</span><br><span class="line">    @Bean(name &#x3D; &quot;scheduler&quot;)</span><br><span class="line">    public Scheduler scheduler() &#123;</span><br><span class="line">        return schedulerFactoryBean().getScheduler();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>监听器</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">@Component</span><br><span class="line">@Order(value &#x3D; 1)</span><br><span class="line">public class ScheduleJobInitListener implements CommandLineRunner &#123;</span><br><span class="line"></span><br><span class="line">    @Autowired</span><br><span class="line">    TaskService scheduleJobService;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run(String... arg0) throws Exception &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            scheduleJobService.initSchedule();</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>CommandLineRunner类似Spring框架的ApplicationListener监听器。官方的解释是:</p>
<blockquote>
<p>Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or Order @Order annotation.<br>接口被用作将其加入spring容器中时执行其run方法。多个CommandLineRunner可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致。</p>
</blockquote>
<p><strong>第二步：读取数据库，加载scheduler调度器</strong></p>
<p>job方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">    public void initSchedule() throws SchedulerException &#123;</span><br><span class="line">        &#x2F;&#x2F; 这里获取任务信息数据</span><br><span class="line">        List&lt;TaskDO&gt; jobList &#x3D; taskMapper.list();</span><br><span class="line">        for (TaskDO task : jobList) &#123;</span><br><span class="line">            if (JobStatusEnum.RUNNING.getCode().equals(task.getJobStatus())) &#123;</span><br><span class="line">                quartzManager.addJob(task);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>添加任务到Quartz调度器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line">     * 添加任务*&#x2F;</span><br><span class="line">    @SuppressWarnings(&quot;unchecked&quot;)</span><br><span class="line">    public void addJob(TaskDO task) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            &#x2F;&#x2F; 创建jobDetail实例，绑定Job实现类</span><br><span class="line">            &#x2F;&#x2F; 指明job的名称，所在组的名称，以及绑定job类</span><br><span class="line">            Class&lt;? extends Job&gt; jobClass &#x3D; (Class&lt;? extends Job&gt;) (Class.forName(task.getBeanClass()).newInstance()</span><br><span class="line">                    .getClass());</span><br><span class="line">            JobDetail jobDetail &#x3D; JobBuilder.newJob(jobClass).withIdentity(task.getJobName(), task.getJobGroup())&#x2F;&#x2F; 任务名称和组构成任务key</span><br><span class="line">                    .build();</span><br><span class="line">            &#x2F;&#x2F; 定义调度触发规则</span><br><span class="line">            &#x2F;&#x2F; 使用cornTrigger规则</span><br><span class="line">            Trigger trigger &#x3D; TriggerBuilder.newTrigger().withIdentity(task.getJobName(), task.getJobGroup())&#x2F;&#x2F; 触发器key</span><br><span class="line">                    .startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND))</span><br><span class="line">                    .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).startNow().build();</span><br><span class="line">            &#x2F;&#x2F; 把作业和触发器注册到任务调度中</span><br><span class="line">            scheduler.scheduleJob(jobDetail, trigger);</span><br><span class="line">            &#x2F;&#x2F; 启动</span><br><span class="line">            if (!scheduler.isShutdown()) &#123;</span><br><span class="line">                scheduler.start();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>Scheduler作为Quartz的核心调度器，有将近50多个API接口，包括任务的添加，暂停，恢复，删除等一系列的API，这里仅介绍一些常用的，想要了解更多可以稍后看下彩蛋部分。</p>
<p>1、start()方法：只有调用start()方法后，Scheduler线程才开始启动触发器trigger，运行job</p>
<p>2、pauseJob(JobKey jobKey) ：根据指定的JobDetail key暂停job。</p>
<p>3、resumeJob(JobKey jobKey) ：根据指定的key恢复一个job。</p>
<p>4、deleteJob(JobKey jobKey) ：删除一个job</p>
<p>5、triggerJob(JobKey jobKey) ：触发一个JobDetail(现在执行)。</p>
<p>6、rescheduleJob(TriggerKey triggerKey, Trigger newTrigger)：</p>
<p>用给定的键删除触发器，并存储新的触发器，它必须与同一个作业相关联（新触发器必须具有指定的作业名和组）-然而，新触发器不必具有与旧触发器相同的名称。</p>
<p><strong>第三步：根据任务调度运行job类</strong></p>
<p>其实这一步是不需要我们编写的，在我们将正确的JobDetail 和 Trigger 表达式加载到任务调度后，调度器会自动触发任务的执行</p>
<p><strong>第四步：实例化job类，注入要运行的service</strong></p>
<p>工厂类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">@Component</span><br><span class="line">public class JobFactory extends AdaptableJobFactory &#123;</span><br><span class="line">    &#x2F;&#x2F;这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.</span><br><span class="line">    &#x2F;&#x2F;为什么需要这个类呢，在我写的这个demo中，大家可以将此类删掉，发现程序也可以正确运行，可是我为什么还是加上呢。</span><br><span class="line">    &#x2F;&#x2F;大家可以看下我们的任务类，大家可以看到Job对象的实例化过程是在Quartz中进行的，这时候我们将spring的东西注入进来，肯定是行不通的，所以需要这个类</span><br><span class="line">    @Autowired</span><br><span class="line">    private AutowireCapableBeanFactory capableBeanFactory;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception &#123;</span><br><span class="line">        &#x2F;&#x2F;调用父类的方法</span><br><span class="line">        Object jobInstance &#x3D; super.createJobInstance(bundle);</span><br><span class="line">        &#x2F;&#x2F;进行注入</span><br><span class="line">        capableBeanFactory.autowireBean(jobInstance);</span><br><span class="line">        return jobInstance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>任务类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@DisallowConcurrentExecution &#x2F;&#x2F;作业不并发</span><br><span class="line">@Component</span><br><span class="line">public class HelloWorldJob implements Job&#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void execute(JobExecutionContext arg0) throws JobExecutionException &#123;</span><br><span class="line">        </span><br><span class="line">        System.out.println(&quot;欢迎使用yyblog,这是一个定时任务 --小卖铺的老爷爷!&quot;+ DateUtils.fullTime(new Date()));</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 好了，大功告成，一个简单的动态配置的定时任务已经完成。是不是so easy，下面我们再来简单实现下其他的几种常用的api吧。</p>
<p>暂停一个job</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void pauseJob(TaskDO task) throws SchedulerException &#123;</span><br><span class="line">        JobKey jobKey &#x3D; JobKey.jobKey(task.getJobName(), task.getJobGroup());</span><br><span class="line">        scheduler.pauseJob(jobKey);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>恢复一个job</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void resumeJob(TaskDO task) throws SchedulerException &#123;</span><br><span class="line">        JobKey jobKey &#x3D; JobKey.jobKey(task.getJobName(), task.getJobGroup());</span><br><span class="line">        scheduler.resumeJob(jobKey);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>删除一个job</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void deleteJob(TaskDO task) throws SchedulerException &#123;</span><br><span class="line">        JobKey jobKey &#x3D; JobKey.jobKey(task.getJobName(), task.getJobGroup());</span><br><span class="line">        scheduler.deleteJob(jobKey);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>立即触发job</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public void runJobNow(TaskDO task) throws SchedulerException &#123;</span><br><span class="line">        JobKey jobKey &#x3D; JobKey.jobKey(task.getJobName(), task.getJobGroup());</span><br><span class="line">        scheduler.triggerJob(jobKey);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>更新job表达式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public void updateJobCron(TaskDO task) throws SchedulerException &#123;</span><br><span class="line"></span><br><span class="line">        TriggerKey triggerKey &#x3D; TriggerKey.triggerKey(task.getJobName(), task.getJobGroup());</span><br><span class="line"></span><br><span class="line">        CronTrigger trigger &#x3D; (CronTrigger) scheduler.getTrigger(triggerKey);</span><br><span class="line"></span><br><span class="line">        CronScheduleBuilder scheduleBuilder &#x3D; CronScheduleBuilder.cronSchedule(task.getCronExpression());</span><br><span class="line"></span><br><span class="line">        trigger &#x3D; trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();</span><br><span class="line"></span><br><span class="line">        scheduler.rescheduleJob(triggerKey, trigger);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>好了，正文部分基本上就这些，不多废话了，本文没有太多的讲解原理，只是简单的应用，水平不够还望大家见谅。</p>
<p>看了上面的效果图是不是还是有种看的见摸不着的感觉，老爷爷这里也做了个线上的实例供大家体验~有兴趣的同学可以亲自试验一下。</p>
<p>实例地址：<a target="_blank" rel="noopener" href="http://www.laoyeye.net/management/index">http://www.laoyeye.net/management/index</a>  账号/密码：test/123456  菜单：系统设置/计划任务</p>
<p> 当然了还有最重要的源码和API文档我也不会忘的。</p>
<p>源码地址：<a target="_blank" rel="noopener" href="https://github.com/allanzhuo/yyblog">https://github.com/allanzhuo/yyblog</a></p>
<p>Quartz文档地址：<a target="_blank" rel="noopener" href="https://github.com/allanzhuo/yyblog/tree/master/doc">https://github.com/allanzhuo/yyblog/tree/master/doc</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2020/11/11/develop/Spring+Quartz%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/develop/" rel="tag">develop</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/11/11/develop/Python%E9%87%87%E9%9B%86linux%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%95%B0%E6%8D%AE%E5%9C%A8Django%20Web%E7%95%8C%E9%9D%A2%E5%B1%95%E7%A4%BA/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            Python采集linux服务器数据在Django Web界面展示.md
          
        </div>
      </a>
    
    
      <a href="/2020/11/11/develop/%E5%88%AB%E7%94%A8Date%E4%BA%86%EF%BC%8CJava8%E6%96%B0%E7%89%B9%E6%80%A7%E4%B9%8B%E6%97%A5%E6%9C%9F%E5%A4%84%E7%90%86%EF%BC%8C%E7%8E%B0%E5%9C%A8%E5%AD%A6%E4%BC%9A%E4%B9%9F%E4%B8%8D%E8%BF%9F/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">别用Date了，Java8新特性之日期处理，现在学会也不迟.md</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> TzWind
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        由 <a href="https://hexo.io" target="_blank">Hexo</a> 强力驱动
        <span class="division">|</span>
        主题 - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Hexo"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" target="_blank" rel="noopener" href="http://www.baidu.com">百度</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友链</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2019/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>